<template>
  <el-date-picker
    v-model="formData[data.field]"
    type="datetimerange"
    clearable
    :disabled="data.disabled"
    value-format="YYYY-MM-DD HH:mm:ss"
    :shortcuts="shortcuts"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    range-separator="-"
    @change="searchFun"
  >
  </el-date-picker>
</template>

<script lang="ts">
import { defineComponent, computed, ref } from 'vue'
import { baseForm } from '@/common/mixins/index'
import { newDate } from '@/common/utils/common'

export default defineComponent({
  name: 'DateTimeRange',
  props: {
    form: {
      type: Object,
      default: () => ({})
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['onSearchFun', 'update:form'],
  setup(props, { emit }) {
    const shortcuts = [
      // 日期时间的快捷搜索项（最近一周，最近一个月，最近三个月）
      {
        text: '最近一周',
        value: () => {
          const end = newDate()
          const start = newDate()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        }
      },
      {
        text: '最近一个月',
        value: () => {
          const end = newDate()
          const start = newDate()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          return [start, end]
        }
      },
      {
        text: '最近三个月',
        value: () => {
          const end = newDate()
          const start = newDate()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        }
      }
    ]
    const formData = computed({
      get: () => props.form,
      set: (val) => emit('update:form', val)
    })

    const lock = ref(false)

    const searchFun = () => {
      if (lock.value) {
        return
      }
      lock.value = true
      baseForm.searchFun(emit)
      setTimeout(() => {
        lock.value = false
      }, 500)
    }
    return { searchFun, formData, shortcuts }
  }
})
</script>

<style lang="stylus" scoped></style>
